<?php
namespace app\zmt\controller;


use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use api\zmt\model\RegistrationModel;
use api\zmt\validate\registrationValidate;
use app\zmt\model\bannerModel;
use app\zmt\model\CodeModel;
use app\zmt\model\UserModel;
use app\zmt\validate\UserValidate;
use cmf\controller\AdminBaseController;
use Darabonba\OpenApi\Models\Config;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class UserController extends AdminBaseController
{
    public function index(){
        $data = UserModel::select();
        return $this->fetch('index',[
            'data' => $data,
        ]);
    }
    public function totolgSwitch(){
        $id = input('id/d');
        $user = UserModel::find($id);

        if (!$user) {
            $this->error('新闻不存在');
        }

        // 切换状态
        $user->switch = $user->switch ? 0 : 1;
        if ($user->save()) {
            $this->success('切换成功');
        } else {
            $this->error('切换失败');
        }
    }
    public function add(){
        return $this->fetch();
    }
    public function addPost(){
        $data = input('post.');
        if (empty($data)){
            return json(['code'=>0,'msg'=>'数据不全请重新添加','data'=>$data]);
        }
        $exit = UserModel::where('mobile',$data['mobile'])->find();
        if ($exit){
            return json(['code'=>0,'msg'=>'你的手机号已存在，请重新提交手机号','data'=>null]);
        }
        if (!checkSmsCode($data['mobile'],$data['code'])){
            return error('验证码失效或已过期');
        }
        $validate = new UserValidate();
        if (!$validate->scene('registration')->check($data)){
            return error($validate->getError());
        }
        $salt = RandStar();
        $password = $data['password'].$salt;
        $data['salt'] = $salt;
        $data['password']=md5($password);
        $data['create_time']=time();
        $model = UserModel::create($data);
        if ($model){
            return success('创建用户成功，尝试登录一下');
        }else{
            return error('创建失败，请重新进行添加');
        }
    }
    public function sendAliSms()
    {
        $code = mt_rand(1111, 9999);
        $mobile = input('mobile');
        $config = new Config([
            // 从阿里云获取
            'accessKeyId' => config('app.aliSms.accessKeyId'),
            'accessKeySecret' => config('app.aliSms.accessKeySecret'),
        ]);

        $config->endpoint = "dysmsapi.aliyuncs.com";
        $client = new Dysmsapi($config);

        // 运行时参数超时设置，仅对使用了该运行时参数实例的请求有效
        $runtimeOptions = new RuntimeOptions();
        // true 忽略证书校验
        $runtimeOptions->ignoreSSL = true;

        $sendSmsRequest = new SendSmsRequest();
        // 手机号
        $sendSmsRequest->phoneNumbers = $mobile;
        // 签名名称
        $sendSmsRequest->signName = '阿里云短信测试';
        // 模板CODE
        $sendSmsRequest->templateCode = 'SMS_154950909';
        // 生成随机数作为验证码
        $sendSmsRequest->templateParam = json_encode(['code' => $code]);
        try {
            $response = $client->sendSmsWithOptions($sendSmsRequest, $runtimeOptions);
        } catch (\Exception $exception) {
            halt($exception->getMessage());
        }
        if ($response->body->code == 'OK') {
            echo '短信发送成功！';
            $data = [
                'mobile' =>$mobile,
                'code' =>$code,
                'send_time'=>time(),
            ];
            $model = CodeModel::create($data);
            if ($model){
                return json(['code'=>1,'msg'=>'数据库存储成功','data'=>null]);
            }
        } else {
            halt($response->body->message);
        }

    }

    public function edit(){
        $id = input('id');
        $model = UserModel::find($id);
        return $this->fetch('edit',[
            'data' => $model,
        ]);
    }
    public function editPost()
    {
        if (request()->isPost()) {
            $data = request()->post();
            $exit = UserModel::find($data['id']);
            $validate = new registrationValidate();
            if (!$validate->scene('edit')->check($data)) {
                return error($validate->getError());
            }
            if (!checkSmsCode($data['mobile'],$data['code'])){
                return error('验证码失效或已过期');
            }
            $exit->user_name = $data['user_name'];
            $exit->image = $data['image'];
            $exit->school_name = $data['school_name'];
            $exit->school_address = $data['school_address'];
            $exit->create_time = time();
            if ($exit->save()) {
                return success('修改信息成功', $exit);
            } else {
                return error('修改信息失败');
            }
        }
    }
    public function order(){
        parent::listOrders(new UserModel());
        $this->success('排序成功');
    }
    public function delete(){
        $id = input('id');
        if (UserModel::destroy($id)){
            $this->success('删除成功');
        }else {
            $this->success('删除成功');
        }
    }
}